package com.csust.zerocode.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.csust.zerocode.constant.UserConstant;
import com.csust.zerocode.exception.BusinessException;
import com.csust.zerocode.exception.ErrorCode;
import com.csust.zerocode.model.dto.user.UserQueryDTO;
import com.csust.zerocode.model.enums.UserRoleEnum;
import com.csust.zerocode.model.vo.user.LoginUserVO;
import com.csust.zerocode.model.vo.user.UserVO;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.csust.zerocode.model.entity.User;
import com.csust.zerocode.mapper.UserMapper;
import com.csust.zerocode.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.csust.zerocode.constant.OrderConstant.ASC;
import static com.csust.zerocode.constant.UserConstant.*;
import static com.csust.zerocode.model.entity.table.UserTableDef.USER;

/**
 *  服务层实现。
 *
 * @author 钰玟
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String useRole) {
        //1. 数据校验
        if(StrUtil.hasBlank(userAccount,userPassword,checkPassword)){
            // 是否有空格
            throw new BusinessException(ErrorCode.PARAMS_ERROR, UserConstant.PARAMS_IS_NULL);
        }
        if(userAccount.length()<UserConstant.ACCOUNT_MIN_LENGTH ){
            // 账户是否符合 长度要求
            throw new BusinessException(ErrorCode.PARAMS_ERROR,ACCOUNT_IS_SHORT);
        }
        if(userPassword.length() <PASSWORD_MIN_LENGTH || checkPassword.length()< PASSWORD_MIN_LENGTH){
            // 密码是否符合 长度要求
            throw new BusinessException(ErrorCode.PARAMS_ERROR,PASSWORD_IS_SHORT);
        }
        if(!userPassword.equals(checkPassword)){
            //两次密码不一致
            throw new BusinessException(ErrorCode.PARAMS_ERROR,DOUBLE_PASSWORD_NOT_EQUAL);
        }
//        if(useRole==null){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
        if("admin".equals(useRole)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //2. 判断 用户名是否唯一
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount",userAccount);
        Long accountNum = this.mapper.selectCountByQuery(queryWrapper);
        if(accountNum>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,ACCOUNT_REPEATED);
        }
        //3. 加密 数据
        String encryptPassword = getEncryptPassword(userPassword);

        //4. 注册该用户(插入数据)
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());
        user.setUserRole(useRole);
        boolean saveResult = this.save(user);
        // 判断是否 注册成功
        if(!saveResult){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,FAIL_REGISTER);
        }
        return user.getId();
    }
    /**
     * 用户登录
     * @param userAccount 登录账号
     * @param userPassword 登录密码
     * @return VO对象 (脱敏后的对象)
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1. 数据校验
        if(StrUtil.hasBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, UserConstant.PARAMS_IS_NULL);
        }
        if(userAccount.length()<UserConstant.ACCOUNT_MIN_LENGTH){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,ACCOUNT_ERROR);
        }
        if(userPassword.length() <PASSWORD_MIN_LENGTH){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,PASSWORD_ERROR);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount",userAccount);
        // 密码加密
        String encryptPassWord = this.getEncryptPassword(userPassword);
        queryWrapper.eq("userPassword",encryptPassWord);
        User user = this.mapper.selectOneByQuery(queryWrapper);
        // 用户不存在
        if(user==null){
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,FAIL_LOGIN);
        }
        // 记录用户的登录状态
        request.getSession().setAttribute(USER_LOGIN_STATE,user);
//        //将登录态保存至sa-token
//        StpKit.SPACE.login(user.getId());
//        StpKit.SPACE.getSession().set(USER_LOGIN_STATE,user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     * @param request 请求
     * @return 用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否登录
        //1. 从Session 中获取存入的User对象
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        //强转
        User currentUser = (User) userObj;
        if(currentUser==null || currentUser.getId()==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //从数据库 查询( 追求性能可以注释，直接返回上述结果)
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取脱敏的已登录用户信息
     * @param user 用户
     * @return 脱敏对象
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if(user == null){
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user,loginUserVO);
        return loginUserVO;
    }

    @Override
    public Boolean userLogout(HttpServletRequest request) {
        //先判断是否登录
        Object user = request.getSession().getAttribute(USER_LOGIN_STATE);
        if(user==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,NO_LOGIN);
        }
        //更新活跃时间
        User currentUser = (User) user;
        currentUser.setActiveTime(LocalDateTime.now());
        boolean updated = this.updateById(currentUser);
        if(!updated){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"退出登录失败");
        }
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return Boolean.TRUE;
    }
    /**
     * 获取user vo
     * @param user user
     * @return userVO
     */
    @Override
    public UserVO getUserVO(User user) {
        if(user == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        return userVO;
    }
    /**
     * 获取user列表
     * @param userList 列表
     * @return VO列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if(CollUtil.isEmpty(userList)){
            return new ArrayList<>();
        }
        //使用流转换
//        return userList.stream().map(user -> {
//            UserVO userVO = new UserVO();
//            BeanUtil.copyProperties(user,userVO);
//            return userVO;
//        }).collect(Collectors.toList());

        //直接调用方法
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper getUserQueryWrapper(UserQueryDTO userQueryDTO) {
        if(userQueryDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, UserConstant.PARAMS_IS_NULL);
        }
        //提取查询的字段
        Long userId = userQueryDTO.getId();
        String userAccount = userQueryDTO.getUserAccount();
        String userName = userQueryDTO.getUserName();
        String userProfile = userQueryDTO.getUserProfile();
        String userRole = userQueryDTO.getUserRole();
        String searchText = userQueryDTO.getSearchText();//搜索字段
        Integer status = userQueryDTO.getStatus();
        String sortField = userQueryDTO.getSortField();
        String sortOrder = userQueryDTO.getSortOrder();
        //构建query对象
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",userId,ObjUtil.isNotNull(userId));
        queryWrapper.like("userAccount",userAccount,StrUtil.isNotBlank(userAccount));
        queryWrapper.like("userName",userName,StrUtil.isNotBlank(userName));
        queryWrapper.like("userProfile",userProfile,StrUtil.isNotBlank(userProfile));
        queryWrapper.eq("userRole",userRole,StrUtil.isNotBlank(userRole));
        queryWrapper.eq("status",status,ObjUtil.isNotNull(status));

        //多字段匹配
        if(StrUtil.isNotBlank(searchText)){//用户名/姓名/邮箱
            queryWrapper.like("userAccount",searchText)
                    .or(USER.USER_NAME.like(searchText))
                    .or(USER.EMAIL.like(searchText));

        }
        queryWrapper.orderBy(sortField,sortOrder.equals(ASC));
        //返回query
        return queryWrapper;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }


    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "yuwen";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }
}
